package handler

import (
	"math"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

func (h *Handler) GetAllRecords(c *gin.Context) {
	// 获取并验证参数
	locationID := c.Param("location_id")
	if locationID == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "location_id is required",
		})
		return
	}

	// 获取分页参数，设置默认值
	page := c.DefaultQuery("page", "1")
	pageSize := c.DefaultQuery("page_size", "10")

	// 调用 service 层
	records, total, err := h.dataService.GetAllRecords(locationID, page, pageSize)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    http.StatusInternalServerError,
			"message": err.Error(),
		})
		return // 记得在错误处理后返回
	}

	// 计算总页数
	pageSizeInt, _ := strconv.Atoi(pageSize)
	totalPages := int(math.Ceil(float64(total) / float64(pageSizeInt)))

	// 返回规范化的响应
	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "success",
		"data": gin.H{
			"records": records,
			"pagination": gin.H{
				"currentPage": page,
				"pageSize":    pageSize,
				"total":       total,
				"totalPages":  totalPages,
			},
		},
	})
}

func (h *Handler) GetRecordID(c *gin.Context) {
	var req struct {
		LocationID string `json:"locationID" binding:"required"`
		UserID     string `json:"userID" binding:"required"`
	}
	err := c.ShouldBindJSON(&req)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
		return
	}
	err = h.dataService.GetRecordID(req.LocationID, req.UserID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "success"})
}

func (h *Handler) GetRecordDetail(c *gin.Context) {
	// Implementation for getting record detail
}

func (h *Handler) DeleteRecord(c *gin.Context) {
	// Implementation for deleting a record
}

func (h *Handler) PostFileSHA(c *gin.Context) {
	// Implementation for posting file SHA
}
